package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.ActCategory;
import com.ruoyi.system.domain.ActTitle;
import com.ruoyi.system.domain.Game;
import com.ruoyi.system.dto.ResultDto;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IActCategoryService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.vo.ActStatVO;
import com.ruoyi.system.vo.ActVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.Act;
import com.ruoyi.system.service.IActService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 参赛作品Service业务层处理
 *
 * @author ruoyi
 * @date 2021-11-28
 */
@Service
public class ActServiceImpl implements IActService
{
    @Autowired
    private ActMapper actMapper;

    @Autowired
    private ActCategoryMapper actCategoryMapper;

    @Autowired
    private GameMapper gameMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private ActTitleMapper actTitleMapper;

    @Autowired
    private IActCategoryService actCategoryService;

    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询参赛作品
     *
     * @param id 参赛作品主键
     * @return 参赛作品
     */
    @Override
    public Act selectActById(Long id)
    {
        return actMapper.selectActById(id);
    }

    /**
     * 查询参赛作品列表
     *
     * @param act 参赛作品
     * @return 参赛作品
     */
    @Override
    public List<Act> selectActList(Act act, SysUser sysUser)
    {
        return actMapper.selectActList(act);
    }

    /**
     * 新增参赛作品
     *
     * @param act 参赛作品
     * @return 结果
     */
    @Override
    public int insertAct(Act act)
    {
        //获取作品类别名称
        if(act.getCategoryId() != null){
            ActCategory actCategory = actCategoryMapper.selectActCategoryById(act.getCategoryId());
            if(actCategory != null){
                act.setCategoryName(actCategory.getName());
            }
        }

        //获取大赛名称
        if(act.getGameId() != null){
            Game game = gameMapper.selectGameById(act.getGameId());
            if(game != null){
                act.setGameName(game.getName());
            }
        }

        //获取命名标题
        if(act.getTitleId() != null){
            ActTitle actTitle = actTitleMapper.selectActTitleById(act.getTitleId());
            if(actTitle != null){
                act.setTitle(actTitle.getTitle());
            }
        }

        act.setCreateTime(DateUtils.getNowDate());
        return actMapper.insertAct(act);
    }

    /**
     * 修改参赛作品
     *
     * @param act 参赛作品
     * @return 结果
     */
    @Override
    public int updateAct(Act act)
    {
        //获取作品类别名称
        if(act.getCategoryId() != null){
            ActCategory actCategory = actCategoryMapper.selectActCategoryById(act.getCategoryId());
            if(actCategory != null){
                act.setCategoryName(actCategory.getName());
            }
        }

        //获取大赛名称
        if(act.getGameId() != null){
            Game game = gameMapper.selectGameById(act.getGameId());
            if(game != null){
                act.setGameName(game.getName());
            }
        }

        //获取命名标题
        if(act.getTitleId() != null){
            ActTitle actTitle = actTitleMapper.selectActTitleById(act.getTitleId());
            if(actTitle != null){
                act.setTitle(actTitle.getTitle());
            }
        }
        act.setUpdateTime(DateUtils.getNowDate());
        return actMapper.updateAct(act);
    }

    /**
     * 批量删除参赛作品
     *
     * @param ids 需要删除的参赛作品主键
     * @return 结果
     */
    @Override
    public int deleteActByIds(String ids)
    {
        return actMapper.deleteActByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除参赛作品信息
     *
     * @param id 参赛作品主键
     * @return 结果
     */
    @Override
    public int deleteActById(Long id)
    {
        return actMapper.deleteActById(id);
    }

    /**
     * 导入作品数据
     * @param actVos
     * @param gameId
     * @param curUser 当前登录用户
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultDto importActData(List<ActVO> actVos,Long gameId,SysUser curUser){
        ResultDto resultDto = new ResultDto();
        //校验数据
        if(gameId == null || gameId <= 0){
            resultDto.setMessage("请选择大赛名称");
            return  resultDto;
        }
        if(actVos == null || actVos.size() == 0){
            resultDto.setMessage("导入的数据为空");
            return resultDto;
        }

        Game game = gameMapper.selectGameById(gameId);
        if(game == null){
            resultDto.setMessage("请选择大赛名称");
            return  resultDto;
        }

        //查询有叶子节点的父节点集合
        List<ActCategory> parentTreeNodes = actCategoryService.findTreeParentNodes();
        String parentCategoryNames = "";
        if(parentTreeNodes != null && parentTreeNodes.size() > 0){
            for(ActCategory category : parentTreeNodes){
                parentCategoryNames += category.getName() + ",";
            }
        }

        SysDept curDept = sysDeptMapper.selectDeptById(curUser.getDeptId());
        SysDept curSchool = null;

        List<String> actNos = new ArrayList<>();
        for(int i=0; i<actVos.size();i++){
            //Act act = new Act();

            int row = i + 2;
            String prefixMsg = "第" + row + "行的";
            ActVO actVO = actVos.get(i);
            actVO.setGameId(gameId);

            if(actNos.contains(actVO.getActNo())){
                resultDto.setMessage("导入的表格中【参赛编号】"+ actVO.getActNo() +" 存在重复数据！" );
                return  resultDto;
            }else{
                actNos.add(actVO.getActNo());
            }


            if(StringUtils.isBlank(actVO.getCategoryName())){
                resultDto.setMessage(prefixMsg +"【作品类别】为空！" );
                return  resultDto;
            }

            //作品类别不能为父级节点
            if(StringUtils.isNotBlank(parentCategoryNames) && parentCategoryNames.contains(actVO.getCategoryName() + ",")){
                resultDto.setMessage(prefixMsg +"【作品类别】名称错误！" );
                return  resultDto;
            }

            if(StringUtils.isBlank(actVO.getTitle())){
                resultDto.setMessage(prefixMsg + "【命题名称】为空！");
                return  resultDto;
            }

            if(StringUtils.isBlank(actVO.getActNo())){
                resultDto.setMessage(prefixMsg + "【参赛编号】为空！");
                return  resultDto;
            }

            if(StringUtils.isBlank(actVO.getActName())){
                resultDto.setMessage(prefixMsg + "【作品名称】为空！");
                return  resultDto;
            }

            if(StringUtils.isBlank(actVO.getAuthor())){
                resultDto.setMessage(prefixMsg + "【作者】为空！");
                return  resultDto;
            }

            if(StringUtils.isBlank(actVO.getAuthorPhone())){
                resultDto.setMessage(prefixMsg + "【作者电话】为空！");
                return  resultDto;
            }

            //校验是否存在相同参数编号的作品
            if(isExistActNo(actVO.getActNo(), gameId,null)){
                resultDto.setMessage(prefixMsg + "【参赛编号】"+ actVO.getActNo() +"已存在！");
                return  resultDto;
            }

            // 查看类别是否存在
            List<ActCategory> actCategories = actCategoryMapper.selectListByCategoryName(actVO.getCategoryName());
            if(actCategories == null || actCategories.size() == 0){
                resultDto.setMessage(prefixMsg + "【作品类别】不存在！");
                return  resultDto;
            }else{
                actVO.setCategoryId(actCategories.get(0).getId());
                actVO.setCategoryName(actCategories.get(0).getName());
            }

            //查看命题名称是否存在
            List<ActTitle> titles = actTitleMapper.selectByGameIdAndTitleAndCategoryId(actVO);
            if(titles == null || titles.size() == 0){
                resultDto.setMessage(prefixMsg + "【命题名称】不存在！");
                return  resultDto;
            }else{
                actVO.setTitle(titles.get(0).getTitle());
                actVO.setTitleId(titles.get(0).getId());
            }

            if(StringUtils.isNotBlank(actVO.getSchool())){
                actVO.setSchool(actVO.getSchool().trim());
            }
            if(StringUtils.isNotBlank(actVO.getFaculty())){
                actVO.setFaculty(actVO.getFaculty().trim());
            }

            // 判断当前用户是否是院系的人
            if(curDept.getAncestors().startsWith("0,101")){
                //院系的人时，取当前人学校和院系
                if(curSchool == null){
                    if(curDept.getAncestors().equals("0,101")){
                        curSchool = curDept;
                    }else{
                        curSchool = sysDeptMapper.selectDeptById(curDept.getParentId());
                    }
                }
                if(curSchool != null && StringUtils.isNotBlank(actVO.getSchool())){
                    //判断当前用户导入的作品是否是当前学校的
                    if(curSchool.getDeptName().contains(actVO.getSchool()) == false){
                        resultDto.setMessage(prefixMsg +"【学校】名称不对！" );
                        return  resultDto;
                    }
                }

                actVO.setSchoolId(curSchool.getDeptId());
                actVO.setSchool(curSchool.getDeptName());

//                act.setFacultyId(curDept.getDeptId());
//                act.setFaculty(curDept.getDeptName());
                //查询院系是否存在
                if(StringUtils.isBlank(actVO.getFaculty())){
                    resultDto.setMessage(prefixMsg +"【院系】为空！" );
                    return  resultDto;
                }
                actVO.setParentId(curSchool.getDeptId());
                actVO.setDeptName(actVO.getFaculty());
                //查询学校下的院系是否存在
                List<SysDept> inputFacultys = sysDeptMapper.selectDeptListByNameOrParentId(actVO);
                if(inputFacultys == null || inputFacultys.size() == 0){
                    resultDto.setMessage(prefixMsg +"【院系】不存在！" );
                    return  resultDto;
                }

                actVO.setFacultyId(inputFacultys.get(0).getDeptId());
                actVO.setFaculty(inputFacultys.get(0).getDeptName());
            }else{
                if(StringUtils.isBlank(actVO.getSchool()) || actVO.getSchool().length() < 4){
                    resultDto.setMessage(prefixMsg +"【学校】名称不对！" );
                    return  resultDto;
                }
                if(StringUtils.isBlank(actVO.getFaculty())){
                    resultDto.setMessage(prefixMsg +"【院系】为空！" );
                    return  resultDto;
                }
                //查询学校是否存在
                actVO.setDeptName(actVO.getSchool());
                List<SysDept> inputSchools = sysDeptMapper.selectDeptListByNameOrParentId(actVO);
                if(inputSchools == null || inputSchools.size() == 0){
                    resultDto.setMessage(prefixMsg +"【学校】不存在！" );
                    return  resultDto;
                }
                actVO.setParentId(inputSchools.get(0).getDeptId());
                actVO.setDeptName(actVO.getFaculty());
                //查询学校下的院系是否存在
                List<SysDept> inputFacultys = sysDeptMapper.selectDeptListByNameOrParentId(actVO);
                if(inputFacultys == null || inputFacultys.size() == 0){
                    resultDto.setMessage(prefixMsg +"【院系】不存在！" );
                    return  resultDto;
                }

                actVO.setSchoolId(inputSchools.get(0).getDeptId());
                actVO.setSchool(inputSchools.get(0).getDeptName());
                actVO.setFacultyId(inputFacultys.get(0).getDeptId());
                actVO.setFaculty(inputFacultys.get(0).getDeptName());
            }

        }

        for(int i=0; i<actVos.size();i++) {
            ActVO actVO = actVos.get(i);
            Act act = new Act();
            act.setCreateBy(curUser.getLoginName());
            act.setGameId(game.getId());
            act.setGameName(game.getName());
            act.setActNo(actVO.getActNo());
            act.setActName(actVO.getActName());
            act.setAuthor(actVO.getAuthor());
            act.setAuthorPhone(actVO.getAuthorPhone());
            act.setTeacher(actVO.getTeacher());
            act.setTeacherPhone(actVO.getTeacherPhone());
            act.setRemark(actVO.getRemark());
            act.setMajor(actVO.getMajor());
            act.setCreateTime(DateUtils.getNowDate());
            act.setSchoolId(actVO.getSchoolId());
            act.setSchool(actVO.getSchool());
            act.setFacultyId(actVO.getFacultyId());
            act.setFaculty(actVO.getFaculty());
            act.setCategoryId(actVO.getCategoryId());
            act.setCategoryName(actVO.getCategoryName());
            act.setTitle(actVO.getTitle());
            act.setTitleId(actVO.getTitleId());
            actMapper.insertAct(act);
        }

        resultDto.setSuccess(true);
        return resultDto;
    }

    @Override
    public List<Act> select4StatList(ActStatVO actStatVO){
        return actMapper.select4StatList(actStatVO);
    }

    /**
     * 通过gameId和actNo查询  actNo是否存在
     * @param actNo
     * @param gameId
     * @return
     */
    @Override
    public boolean isExistActNo(String actNo,Long gameId,Long actId){
        List<Act> list = actMapper.selectByGameIdAndActNo(gameId,actNo);
        if(list != null && list.size()>0){
            if(list.size()>1){
                return true;
            }else {
                if(list.get(0).getId().equals(actId)){
                    return false;
                }else{
                    return true;
                }
            }
        }
        return false;
    }



}
